package com.ruoyi.web.controller.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.config.ESConfig;
import com.ruoyi.system.entity.HistoryPointData;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Configuration
public class ElasticSearchClientConfig {

    @Autowired
    ESConfig esConfig;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        log.info("连接ES,连接参数: {}", JSONUtil.toJsonStr(esConfig));
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost(esConfig.getIp(), esConfig.getPort(), "http")));
        log.info("连接成功");
        GetIndexRequest request = new GetIndexRequest("point_data");
        try {
            boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
            if (!exists) {
                CreateIndexResponse point_data = client.indices().create(new CreateIndexRequest("point_data"), RequestOptions.DEFAULT);
                log.info("初始化ES索引：{}",point_data.index());
            }
        } catch (IOException e) {
            log.error("查询初始化索引错误：{}",e.getMessage());
        }
        return client;
    }

}
